<?php

/*
 * +----------------------------------------------------------------------
 * 作 者：weilp
 * +----------------------------------------------------------------------
 * 创建日期：2016-08-27
 * +----------------------------------------------------------------------
 * 文件描述：测验内容>>选择题
 * +----------------------------------------------------------------------
 * 升级记录：
 * +----------------------------------------------------------------------
 */
class QuestionTestSelectAction extends CommonAction
{

    public function get_item_edit($formid)
    {
        // 查询数据
        $model = new QuestionTestSelectModel();
        $item = new QuestionTestSelectItemModel();
        
        $data = $model->field("id,
		                       code,
							   formid,
							   question,
							   score,
							   type,
							   get_field_dict_name('question_test_select', 'type', type) type_name,
							   get_field_dict_name('question_test_select', 'score_rule', score_rule) score_rule,
							   get_user_name(operator) operator,
							   get_formate_date(update_date) update_date")
            ->where("id = '" . $formid . "'")
            ->find();
        // 查询当前选择题选项
        $data['item_list'] = $item->field("id,
										   intro,
										   is_correct,
										   is_mutual,
										   seq,
										   score,
										   get_question_test_select_item_logic(id) logic")
            ->where("selectid = '" . $data['id'] . "'")
            ->order("seq ASC")
            ->select();
        return $data;
    }

    /**
     * Enter description here .
     * ..
     * 
     * @param unknown_type $roomid            
     * @param unknown_type $item_id            
     * @param unknown_type $userid            
     * @return unknown
     */
    public function get_item_detail($roomid, $item_id, $userid)
    {
        // 查询数据
        if (! empty($roomid)) {
            $model = new RoomCourseTestSelectModel();
            $item = new RoomCourseTestSelectItemModel();
            $answer = new RoomCourseTestSelectAnswerModel();
            $where['oldid'] = $item_id;
            $where['roomid'] = $roomid;
        } else {
            $model = new CourseTestSelectModel();
            $item = new CourseTestSelectItemModel();
            $answer = new CourseTestSelectAnswerModel();
            $where['id'] = $item_id;
        }
        $data = $model->field("id,
							   testid,
							   question,
							   answer,
							   score,
							   type,
							   get_field_dict_name('course_test_select', 'type', type) type_name")
            ->where($where)
            ->find();
        
        // 查询当前选择题选项
        $data['item_list'] = $item->field("id,
										   intro,
										   is_correct,
										   seq")
            ->where("selectid = '" . $data['id'] . "'")
            ->order("seq ASC")
            ->select();
        
        // 查询当前用户作答情况
        $data['user_answer'] = $answer->field("answer,
											   score")
            ->where("selectid = '" . $data['id'] . "'
									  	   and operator = '" . $userid . "'")
            ->find();
        return $data;
    }

    /**
     * 题目添加页面
     */
    public function add()
    {
        // 当前所剩分值
        $roomid = $this->_request('formid');
        
        $this->assign('item_info', $this->get_form_info($this->_request('formid'))); // 课程基本信息（头部显示）
        $this->assign('type_list', set_field_dict_list('question_test_select', 'type'));
        $this->assign('score_type_list', set_field_dict_list('question_test_select', 'score_rule'));
        $this->display();
    }

    /**
     * 将题目添加至数据库
     */
    public function insert()
    {
        $formid = $this->_request('formid');
        $mode = $this->_request('mode');
        $select = new QuestionTestSelectModel();
        $item = new QuestionTestSelectItemModel();
        $select->startTrans(); // 启动事务
        
        if (false !== $select->create()) {
            $insertId = $select->add();
            if (false !== $insertId) {
                $data = R('Admin/QuestionTestEdit/add_item_info', array(
                    $formid,
                    'select',
                    $insertId
                ));
                if (false !== $data) {
                    // 添加选择题选项
                    $select_item = $this->_request('select_item');
                    $is_correct = $this->_request('is_correct');
                    $is_mutual = $this->_request('is_mutual');
                    $score = $this->_request('score_option');
                    foreach ($select_item as $key => $value) {
                        if (empty($value)) {
                            continue;
                        }
                        $item_data['selectid'] = $insertId;
                        $item_data['intro'] = $value;
                        $item_data['is_correct'] = $is_correct[$key];
                        $item_data['is_mutual'] = $is_mutual[$key];
                        $item_data['score'] = $score[$key];
                        $item_data['seq'] = $key;
                        
                        // 将选项数据添加至数据库
                        $data = $item->create($item_data, 1);
                        if (false !== $data) {
                            if (false === $item->add($data)) {
                                $select->rollback(); // 回滚事务
                                $this->error('选择题选项添加失败！');
                            }
                        } else {
                            $select->rollback(); // 回滚事务
                            $this->error('选择题选项添加失败！' . $item->getError());
                        }
                    }
                    // 执行成功后的操作
                    $select->commit(); // 提交事务
                    $this->success('题目添加成功！', __APP__ . '?g=Admin&m=QuestionTestEdit&a=index&formid=' . $formid . '&mode=' . $mode . '#select_' . $insertId);
                } else {
                    $select->rollback(); // 回滚事务
                    $this->error('题目添加失败1！');
                }
            } else {
                $select->rollback(); // 回滚事务
                $this->error('题目添加失败2！');
            }
        } else {
            $select->rollback(); // 回滚事务
            $this->error('题目添加失败3！' . $select->getError());
        }
    }

    /**
     * 题目修改页面
     */
    public function edit()
    {
        // 查询当前选择题信息
        $model = new QuestionTestSelectModel();
        $item = new QuestionTestSelectItemModel();
        
        $data = $model->where("id = '" . $this->_request('questionid') . "'")
            ->find();
        $this->assign('data', $data);
        
        // 查询当前选项信息
        $item_list = $item->where("selectid = '" . $data['id'] . "'")
            ->order("seq ASC")
            ->select();
        $this->assign('item_list', $item_list);
        
        // 获得问卷基本信息
        $this->assign('course_info', $this->get_form_info($this->_request('formid')));
        $this->assign('type_list', set_field_dict_list('question_test_select', 'type'));
        $this->assign('score_type_list', set_field_dict_list('question_test_select', 'score_rule'));
        
        $this->display();
    }

    /**
     * 将题目信息更新至数据库
     */
    public function update()
    {
        $select = new QuestionTestSelectModel();
        $item = new QuestionTestSelectItemModel();
        
        $select->startTrans(); // 启动事务
        if (false !== $select->create()) {
            if (false !== $select->save()) {
                // 更新选择题选项
                $itemid = $this->_request('itemid');
                $select_item = $this->_request('select_item');
                $score_option = $this->_request('score_option');
                $is_correct = $this->_request('is_correct');
                $is_mutual = $this->_request('is_mutual');
                $score = $this->_request('score');
                foreach ($itemid as $key => $value) {
                    if (empty($itemid[$key])) {
                        continue;
                    }
                    $item_data['id'] = $value;
                    $item_data['selectid'] = $this->_request('id');
                    $item_data['intro'] = $select_item[$key];
                    $item_data['score'] = $score_option[$key];
                    $item_data['is_correct'] = $is_correct[$key];
                    $item_data['is_mutual'] = $is_mutual[$key];
                    $item_data['seq'] = $key;
                    
                    if ($value == '-1') { // 添加新选项
                        unset($item_data['id']); // 销毁id
                        $data = $item->create($item_data, 1);
                        if (false !== $data) {
                            if (false === $item->add($data)) {
                                $select->rollback(); // 回滚事务
                                $this->error('选择题选项添加失败！');
                            }
                        } else {
                            $select->rollback(); // 回滚事务
                            $this->error('选择题选项更新失败！' . $item->getError());
                        }
                    } else { // 更新旧选项
                        $data = $item->create($item_data, 0);
                        if (false !== $data) {
                            if (false === $item->save($data)) {
                                $select->rollback(); // 回滚事务
                                $this->error('选择题选项更新失败！');
                            }
                        } else {
                            $select->rollback(); // 回滚事务
                            $this->error('选择题选项更新失败！' . $item->getError());
                        }
                    }
                }
                // 执行成功后的操作
                $select->commit(); // 提交事务
                
                $this->success('题目更新成功！', __APP__ . '?g=Admin&m=QuestionTestEdit&a=index&formid=' . $this->_request('formid') . '&mode=edit' . '#select_' . $this->_request('id'));
            } else {
                $select->rollback(); // 回滚事务
                $this->error('题目更新失败！');
            }
        } else {
            $select->rollback(); // 回滚事务
            $this->error('题目更新失败！' . $select->getError());
        }
    }

    /**
     * 删除题目信息
     */
    public function delete()
    {
        $id = $this->_request('questionid');
        if (! empty($id)) {
            $model = new QuestionTestSelectModel();
            $item = new QuestionTestSelectItemModel();
            
            $model->startTrans(); // 启动事务
                                  
            // 首先删除选择题选项信息
            if (false !== $item->where("selectid = '" . $id . "'")->delete()) {
                // 测验中的item_info字段
                $data = $model->field('id, formid')
                    ->where("id = '" . $id . "'")
                    ->find();
                
                // 删除选择题基本信息
                if (false !== $model->where("id = '" . $id . "'")->delete()) {
                    // 删除测验中的item_info字段
                    $result = R('Admin/QuestionTestEdit/delete_item_info', array(
                        $data['formid'],
                        'select',
                        $data['id']
                    ));
                    if ($result) {
                        $model->commit(); // 提交事务
                        $this->ajaxReturn(null, '删除成功！', 1);
                    } else {
                        $model->rollback(); // 回滚事务
                        $this->ajaxReturn(null, '删除失败！', 0);
                    }
                } else {
                    $model->rollback(); // 回滚事务
                    $this->ajaxReturn(null, '选择题基本信息删除失败！', 0);
                }
            } else {
                $model->rollback(); // 回滚事务
                $this->ajaxReturn(null, '选择题选项删除失败！', 0);
            }
        } else {
            $this->ajaxReturn(null, '未找到要删除的题目！', 0);
        }
    }

    /**
     * 编辑选择题时从数据库删除选项操作
     */
    public function delItem()
    {
        $model = new QuestionTestSelectItemModel();
        if (false !== $model->where("id = '" . $this->_request('id') . "'")
            ->delete()) {
            $this->ajaxReturn(null, '选项从数据库中删除成功！', 1);
        } else {
            $this->ajaxReturn(null, '选项从数据库中删除失败！', 0);
        }
    }

    /**
     * 显示逻辑设置界面
     */
    public function logic_set()
    {
        // echo "logic_set";
        // dump($_REQUEST);
        $formid = $this->_request('formid');
        $mode = 'edit';
        // 查询当前选择题信息
        $model = new QuestionTestSelectModel();
        $item = new QuestionTestSelectItemModel();
        
        $data = $model->where("id = '" . $this->_request('questionid') . "'")
            ->find();
        $this->assign('data', $data);
        
        // 查询当前选项信息
        $item_list = $item->where("selectid = '" . $data['id'] . "'")
            ->order("seq ASC")
            ->select();
        $this->assign('item_list', $item_list);
        
        // 查询所有题目信息
        $alldatamodel = new FormModel();
        $formid = $this->_request('formid');
        $formdata = $alldatamodel->field('id, title, intro, item_info, status')
            ->where("id = '" . $formid . "'")
            ->find();
        
        if (! empty($formdata['item_info'])) {
            $item_info = array();
            $item_info = explode(',', $formdata['item_info']);
            foreach ($item_info as $key => $value) {
                // 根据模块类型获取模块内容
                $item_info_detail = explode(':', $value);
                switch ($item_info_detail[0]) {
                    case 'select':
                        $data = R('Admin/QuestionTestSelect/get_item_' . $mode, array(
                            $item_info_detail[1]
                        ));
                        break;
                    case 'desc':
                        $data = R('Admin/QuestionTestDesc/get_item_' . $mode, array(
                            $item_info_detail[1]
                        ));
                        break;
                    case 'judge':
                        $data = R('Admin/QuestionTestJudge/get_item_' . $mode, array(
                            $item_info_detail[1]
                        ));
                        break;
                    case 'blank':
                        $data = R('Admin/Blank/get_item_' . $mode, array(
                            $item_info_detail[1]
                        ));
                        break;
                    case 'affix':
                        $data = R('Admin/Affix/get_item_' . $mode, array(
                            $item_info_detail[1]
                        ));
                        break;
                    default:
                        $data = array();
                }
                // dump($data);
                if (! empty($data)) {
                    if ($item_info_detail[0] == 'affix') {
                        $item_name = $data["title"];
                    } else {
                        $item_name = $data["question"];
                    }
                    $item_info[$key] = array(
                        'item_type' => $item_info_detail[0],
                        'item_id' => $item_info_detail[1],
                        'item_name' => $this->cutstr_html($item_name, 50),
                        'item_data' => $data
                    );
                }
            }
            // dump($item_info);
            $formdata['item_list'] = $item_info;
        }
        
        $this->assign('formdata', $formdata);
        
        // 获得问卷基本信息
        $this->assign('course_info', $this->get_form_info($this->_request('formid')));
        $this->assign('type_list', set_field_dict_list('question_test_select', 'type'));
        
        $this->display();
    }

    /**
     * 存储逻辑设置
     */
    public function logic_set_save()
    {
        $model = new LogicModel();
        $post_data = $this->_request();
        $formid = $this->_request('formid');
        $post_data_question = $this->_request('question');
        $mode = 'edit';
        if (! empty($post_data['item'])) {
            $delete = $model->where("itemid = '" . $post_data['item'] . "'")->delete();
            if ($delete === false) {
                $model->rollback();
                $this->error('旧逻辑删除失败');
            }
            // 如果为空，则删除之前设置逻辑
            if (! empty($post_data_question)) {
                foreach ($post_data_question as $key => $value) {
                    $adddata['itemid'] = $post_data['item'];
                    $adddata['formid'] = $post_data['formid'];
                    $adddata['questionid'] = $value;
                    $model->startTrans(); // 启动事务
                    $data = $model->create($adddata, 1);
                    if (false !== $data) {
                        $affixdata = $model->add();
                        if (false !== $data) {
                            $model->commit();
                            $this->success('逻辑添加成功！', __APP__ . '?g=Admin&m=QuestionTestEdit&a=index&formid=' . $formid . '&mode=' . $mode);
                        } else {
                            $model->rollback();
                            $this->error('逻辑添加失败');
                        }
                    } else {
                        $model->rollback();
                        $this->error('添加失败' . $model->getError());
                    }
                }
            } else {
                $this->success('逻辑删除成功！', __APP__ . '?g=Admin&m=QuestionTestEdit&a=index&formid=' . $formid . '&mode=' . $mode);
            }
        } else {
            $this->error('您没有选择左边选项');
        }
    }
}
?>